<?php
/**
 * Вход на сайт с помощью сервиса авторизации loginza.ru
 *
 * @author tonatos
 */
class c_loginza_controller extends c_login_controller {

    protected $module = "loginza";

    public function  __construct() {
        parent::__construct();
        global $modx;
        $this->callback=$modx->config["site_url"]."login/loginza.html";
    }
    /*function index() {
        //В процессее...
        global $modx;
        if ($modx->getLoginUserID()) {
            $modx->sendRedirect($modx->makeUrl($this->cabinet));
        }

        $form = new c_form_controller();

        $form->add_varchar("username", "Логин", "", 1);
        $form->add_password("password", "Пароль", "", 1);
        $form->add_checkbox("remember", "Запомнить меня");

        if ($form->data_submitted()) {
            if ($form->is_validate()) {
                $data = $form->get_data();

                if ($this->check($data['username'], $data['password'], $data['remember'])) {
                    $modx->sendRedirect($modx->makeUrl($this->cabinet));
                } else {
                    $form->get_field("password")->set_error("Логин или пароль не верный");
                }
            }
        }
       
        $this->form = $form;
        $this->show("login_form");

    }*/

    public function loginza($param) {

        global $modx;

        // запрос профиля авторизованного пользователя
        $LoginzaAPI = new LoginzaAPI();
        $profile = $LoginzaAPI->getAuthInfo($_POST['token']);

        // проверка на ошибки
        if (is_object($profile) && empty($profile->error_type)) {
            // поиск пользователя в БД

            $fields = $this->get_all_field($profile);

            $url_p = parse_url($profile->provider);

            $identity = new c_web_user_loginza_model();

            if ( ! $identity->find_by("activated!=0 and identity='" . $modx->db->escape($profile->identity) . "'") ) {

                /*
                if (!empty($profile->email)) {
                    $user = $modx->db->get_record("web_user_attributes", "email='" . $modx->db->escape($profile->email) . "'");

                    //нашли по email объединяем
                    if ($user !== false) {
                        $this->loginza_merge($profile->identity, $user, $profile, $url_p['host']);
                        return;
                    }
                }*/

                //Формируем массив POST для регистрации
                $_POST['submitted'] =1;
                $_POST['fullname'] = $fields->fullname;
                $_POST['username'] = $fields->login;
                $_POST['email'] = $fields->email;
                $_SESSION['loginza_profile'] = $profile;
                $this->loginza_register(null);

            } else {
                //Первый вход после объединения, копируем fullname и email

                if ($identity->activated==-1){
                    $web_user = new c_web_users_model($identity->id_user);

                    if (empty($web_user->photo)&&(!empty($profile->photo))){
                        $web_user->photo = $profile->photo;
                    }


                    if (empty($web_user->fullname)&&(!empty($fields->fullname))){
                        $web_user->fullname = $fields->fullname;
                    }
                    $web_user->save();

                    $identity->activated=time();
                    $identity->save();

                }
                $this->auto_login($identity->id_user,1);
                $_SESSION['webUserLoginza'] = $profile->identity;

                $this->return_to_page();

            }
        } else {
            echo $profile->error_type;
        }
    }

    protected function get_all_field($profile) {
        $user_data = new LoginzaUserProfile($profile);

        $result = (object)array();
        $result->fullname = $user_data->genDisplayName();
        $result->login = $user_data->genNickname();
        $result->email = $profile->email;


        return $result;
    }

    protected function loginza_merge($uid, $user, $profile, $openidurl) {

        global $modx;


        $identity = new c_web_user_loginza_model();

        if ($identity->find_by("id_user=$user->internalKey and identity='".$modx->db->escape($uid)."'")===false){

            $identity->id_user  = $user->internalKey;
            $identity->identity = $uid;
            $identity->provider = $openidurl;
            $identity->activated = 0;
            $identity->code = md5($this->generate_password());
            $identity->photo = $profile->photo;
            $identity->save();

        }

        $user_data = new LoginzaUserProfile($profile);
        $model = new c_web_users_model($user->internalKey);

        //Отправляем письмо
        $this->template->fullname = $model->fullname;
        $this->template->username = $model->username;
        $this->template->url = $openidurl;
        $this->template->photo = $profile->photo;
        $this->template->fullname2 = $user_data->genDisplayName();

        $this->template->link = $modx->config['site_url'] . "login/loginza_merged/$identity->id/$identity->code";
        $this->send_mail_from_template($user->email, "Объединение аккаунтов", "mail_loginza_merge");

        //$this->send_register_mail($model->email, $model->username, $model->fullname, $activate);

        //Переходим на страницу подтверждения
        //$modx->sendRedirect("/login/loginza_merge_send.html");
        //die();

        $this->template->email = $user->email;
        $this->template->show("loginza_merge_send");


    }

    public function loginza_register($params){
        global $modx;

        //Подгрузть js скрипт

        $form = new c_form_controller();
        $form->action = "/login/loginza_register.html";
        $form->add_antispam();
        $form->add_username("username", "Имя пользователя", "", true)
                ->set_min(3);
        $form->add_varchar("fullname", "Фамилия И.О.", "", true);

        $form->add_custom("email",new cl_lozinza_emailfield("email", "E-mail", "", "varchar", true));
        $form->add_hidden("merge_by_email");

        //$form->add_email("email", "E-mail", "", true)->check_web_user(false);

        $form->add_hidden("token");

        //Проверка полей через ajax
        if ($params[2]=="ajax_check"){
            $fieldname = $params[3];
            $value = $params[4];

            $field = $form->get_field($fieldname);
            $field->value = $value;
            if ($field->check()){
                echo "set_field_ok('$fieldname');";
            }else{
                echo "set_field_error('$fieldname','$field->error');";
                echo 'jQuery("#a_merge_by_email").click(function(){jQuery("#id_field_merge_by_email").val(1);jQuery("#form_controller").submit(); return false});';
                
            }
            die();
        }

        
        //Сделать проверку токена
        $profile = $_SESSION['loginza_profile'];

        // проверка на ошибки
        if (!is_object($profile) || !empty($profile->error_type)) {
            echo "<p>Ошибка связи с указанной системой (1) <a href='/login.html'>повторить вход</a></p>";
            return;
        }

        if (!empty($_POST['merge_by_email'])){
            $user = $modx->db->get_record("web_user_attributes", "email='" . $modx->db->escape($_POST['email']) . "'");

            //нашли по email объединяем
            if ($user !== false) {
                $url_p = parse_url($profile->provider);
                $this->loginza_merge($profile->identity, $user, $profile, $url_p['host']);
                return;
            }else{
                echo "<p>Ошибка связи с указанной системой (2) <a href='/login.html'>повторить вход</a></p>";
                return;
            }

        }

        $form->reg_ajax_check("loginza/loginza_register");

        $form->set_field_ok(true);

        if ($form->data_submitted()){
            if ($form->is_validate()){

                $data = $form->get_data();

                $user = new c_web_users_model();
                $user->fullname = $data['fullname'];
                $user->username = $data['username'];
                $user->email = $data['email'];
                $user->password=md5($this->generate_password());
                $user->blocked = 0;
                $user->activated = time();

                if (!empty($profile->photo)){
                    $user->photo = $profile->photo;
                }

                $user->save();

                //удаляем возможные запросына объединение
                $modx->db->delete($modx->getFullTableName("web_user_loginza"),"identity='".$modx->db->escape($profile->identity)."'");


                $loginza_row = new c_web_user_loginza_model();

                $loginza_row->id_user = $user->id;
                $loginza_row->identity = $profile->identity;

                $url_p = parse_url($profile->provider);

                $loginza_row->provider = $url_p['host'];
                $loginza_row->activated = time();
                $loginza_row->photo =  $profile->photo;

                $loginza_row->save();

                //Сохраняемся с запоминанием
                $this->auto_login($user->id,1);

                $_SESSION['webUserLoginza'] = $profile->identity;
                
                $this->return_to_page();

                return;
            }
        }

        $this->form=$form;
        $this->show("register");
    }


    public function loginza_merged($params){
        global $modx;

        $id = (int)$params[2];
        $code = $modx->db->escape(trim($params[3]));
        $error = "Неверный код объединения";


        if ((!empty($id))&&(!empty($code))){
            $identity = new c_web_user_loginza_model($id);
            if (!empty($identity->activated)){
                echo "Аккаунт уже объеденен";
            }else{
                if ($identity->code==$code){
                    $identity->code='';
                    $identity->activated=-1;//для определения первого запуска
                    $identity->save();

                    $modx->sendRedirect("/login/loginza_merged_success.html");
                }
            }
        }

        echo $error;
    }

    public function loginza_merged_success(){
        $this->show("merged_success");
        
        
    }
}


?>
